{% extends 'base.html' %}

{% block title %}添加维修记录 - {{ ticket.title }}{% endblock %}

{% block content %}
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title mb-0">添加维修记录: {{ ticket.title }}</h3>
                </div>
                <div class="card-body">
                    <!-- 工单基本信息 -->
                    <div class="alert alert-info">
                        <strong>工单状态:</strong> 
                        <span class="badge 
                            {% if ticket.status == 'pending' %}bg-warning
                            {% elif ticket.status == 'in_progress' %}bg-info
                            {% elif ticket.status == 'completed' %}bg-success
                            {% else %}bg-light text-dark{% endif %}">
                            {{ ticket.get_status_display }}
                        </span>
                        <strong class="ms-3">技术人员:</strong> {{ request.user.username }}
                    </div>

                    <div class="mb-4">
                        <h5>工单信息</h5>
                        <div class="border rounded p-3">
                            <p><strong>创建者:</strong> {{ ticket.created_by.username }}</p>
                            <p><strong>问题描述:</strong></p>
                            <div class="bg-light p-2 rounded">
                                {{ ticket.description|linebreaks }}
                            </div>
                            {% if ticket.assets.exists %}
                            <p class="mt-2"><strong>关联设备:</strong>
                                {% for asset in ticket.assets.all %}
                                <span class="badge bg-light text-dark me-1">{{ asset.code }}</span>
                                {% endfor %}
                            </p>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 维修记录表单 -->
                    <div class="mb-4">
                        <h5>维修记录信息</h5>
                        <div class="border rounded p-3">
                            <form method="post">
                                {% csrf_token %}
                                
                                {% if form.non_field_errors %}
                                <div class="alert alert-danger">
                                    {% for error in form.non_field_errors %}
                                    {{ error }}
                                    {% endfor %}
                                </div>
                                {% endif %}

                                <div class="mb-3">
                                    <label for="{{ form.description.id_for_label }}" class="form-label">{{ form.description.label }}</label>
                                    {{ form.description }}
                                    {% if form.description.errors %}
                                    <div class="text-danger">
                                        {% for error in form.description.errors %}
                                        {{ error }}
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                    <div class="form-text">详细记录维修过程、发现的问题和解决方案</div>
                                </div>

                                <!-- 备件使用选择 -->
                                <div class="mb-3">
                                    <label for="{{ form.spare_part.id_for_label }}" class="form-label">{{ form.spare_part.label }}</label>
                                    {{ form.spare_part }}
                                    {% if form.spare_part.errors %}
                                    <div class="text-danger">
                                        {% for error in form.spare_part.errors %}
                                        {{ error }}
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                    <div class="form-text">从库存中选择使用的备件（可选）</div>
                                </div>

                                <div class="mb-3" id="spare-part-quantity-group" style="display: none;">
                                    <label for="{{ form.spare_part_quantity.id_for_label }}" class="form-label">{{ form.spare_part_quantity.label }}</label>
                                    {{ form.spare_part_quantity }}
                                    {% if form.spare_part_quantity.errors %}
                                    <div class="text-danger">
                                        {% for error in form.spare_part_quantity.errors %}
                                        {{ error }}
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                    <div class="form-text" id="stock-info">当前库存：0</div>
                                </div>

                                <div class="mb-3">
                                    <label for="{{ form.parts_used.id_for_label }}" class="form-label">{{ form.parts_used.label }}</label>
                                    {{ form.parts_used }}
                                    {% if form.parts_used.errors %}
                                    <div class="text-danger">
                                        {% for error in form.parts_used.errors %}
                                        {{ error }}
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                    <div class="form-text">填写使用的其他零件和耗材，多个用逗号分隔</div>
                                </div>

                                <div class="mb-3">
                                    <label for="{{ form.hours_spent.id_for_label }}" class="form-label">{{ form.hours_spent.label }}</label>
                                    {{ form.hours_spent }}
                                    {% if form.hours_spent.errors %}
                                    <div class="text-danger">
                                        {% for error in form.hours_spent.errors %}
                                        {{ error }}
                                        {% endfor %}
                                    </div>
                                    {% endif %}
                                    <div class="form-text">输入实际花费的维修时间（小时）</div>
                                </div>

                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <a href="{% url 'tickets:ticket_detail' ticket.pk %}" class="btn btn-secondary me-md-2">
                                        取消返回
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        💾 保存记录
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 现有维修记录 -->
                    {% if maintenance_records %}
                    <div class="mb-4">
                        <h5>现有维修记录</h5>
                        <div class="border rounded p-3">
                            {% for record in maintenance_records %}
                            <div class="border-bottom pb-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <strong>{{ record.technician.username }}</strong>
                                    <small class="text-muted">{{ record.created_at|date:"Y-m-d H:i" }}</small>
                                </div>
                                <p class="mb-1">{{ record.description }}</p>
                                {% if record.parts_used %}
                                <div class="text-muted">
                                    <small>使用零件: {{ record.parts_used }}</small>
                                </div>
                                {% endif %}
                                {% if record.hours_spent > 0 %}
                                <div class="text-muted">
                                    <small>耗时: {{ record.hours_spent }} 小时</small>
                                </div>
                                {% endif %}
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.container {
    max-width: 800px;
    margin: 20px auto;
}
.card {
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: none;
    border-radius: 8px;
}
.card-header {
    background-color: #2c3e50;
    color: white;
    border-radius: 8px 8px 0 0 !important;
}
.badge {
    font-size: 0.85em;
    padding: 0.5em 0.75em;
}
.btn {
    border-radius: 5px;
    padding: 10px 20px;
}
.alert {
    border-radius: 5px;
    margin-bottom: 20px;
}
.border {
    border-radius: 5px;
}
.form-control {
    border-radius: 5px;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const sparePartSelect = document.getElementById('{{ form.spare_part.id_for_label }}');
    const quantityGroup = document.getElementById('spare-part-quantity-group');
    const stockInfo = document.getElementById('stock-info');
    
    // 备件库存数据（从服务器获取）
    const sparePartStock = {};
    {% for part in form.spare_part.field.queryset %}
    sparePartStock['{{ part.id }}'] = {
        current_stock: {{ part.current_stock }},
        unit: '{{ part.unit|escapejs }}'
    };
    {% endfor %}
    
    // 备件选择变化事件
    sparePartSelect.addEventListener('change', function() {
        const selectedPartId = this.value;
        
        if (selectedPartId) {
            // 显示数量输入框
            quantityGroup.style.display = 'block';
            
            // 更新库存信息
            const partInfo = sparePartStock[selectedPartId];
            if (partInfo) {
                stockInfo.textContent = `当前库存：${partInfo.current_stock} ${partInfo.unit}`;
                
                // 设置最大数量限制
                const quantityInput = document.getElementById('{{ form.spare_part_quantity.id_for_label }}');
                quantityInput.max = partInfo.current_stock;
                
                // 如果当前值超过库存，重置为1
                if (parseInt(quantityInput.value) > partInfo.current_stock) {
                    quantityInput.value = 1;
                }
            }
        } else {
            // 隐藏数量输入框
            quantityGroup.style.display = 'none';
        }
    });
    
    // 初始化时检查是否有选中的备件
    if (sparePartSelect.value) {
        sparePartSelect.dispatchEvent(new Event('change'));
    }
});
</script>
{% endblock %}
